﻿using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Xsl;

namespace YawetagLib.Utilities
{
    public static class XslTransformationBuilder
    {
        public static string Transform(string templatePath, XDocument document,
            params KeyValuePair<string, string>[] arguments)
        {
            StringBuilder builder = new StringBuilder();
            StringWriter writer = new StringWriter(builder);
            XslCompiledTransform template = new XslCompiledTransform();
            template.Load(templatePath);

            XmlDocument xml = new XmlDocument();
            if (document != null) { xml.LoadXml(document.ToString()); }
            else { xml.AppendChild(xml.CreateNode(XmlNodeType.Element, "no-data", string.Empty)); }

            if (xml.DocumentElement != null)
            {
                XsltArgumentList xslArgs = new XsltArgumentList();
                foreach (KeyValuePair<string, string> arg in arguments)
                {
                    xslArgs.AddParam(arg.Key, string.Empty, arg.Value);
                }

                template.Transform(new XmlNodeReader(xml.DocumentElement), xslArgs, writer);

                return builder.ToString();
            }

            return string.Empty;
        }
    }
}
